﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Sockets;

namespace SerialBrowserBridge.WebServer
{
    public class Response
    {
        private bool _hasResponse;
        public bool HasResponse {
            get { return _hasResponse || Content.Length > 0; }
            set { _hasResponse = value; }
        }

        private String _mimeType = "text/html";
        public String MimeType
        {
            get { return _mimeType; }
            set {
                if (_mimeType != value)
                {
                    _mimeType = value;
                    HasResponse = true;
                }
            }
        }

        private String _status = "200 OK";
        public String Status
        {
            get { return _status; }
            set
            {
                if (_status != value)
                {
                    _status = value;
                    HasResponse = true;
                }
            }
        }

        private String _version = "1.0";
        public String Version
        {
            get { return _version; }
            set
            {
                if (_version != value)
                {
                    _version = value;
                    HasResponse = true;
                }
            }
        }

        private MemoryStream _content = new MemoryStream();
        public MemoryStream Content
        {
            get { return _content; }
            set { _content = value; }
        }

        public void Write(string text)
        {
            var streamWriter = new StreamWriter(_content);
            streamWriter.Write(text);
            streamWriter.Flush();
            HasResponse = true;
        }

        public void Render(NetworkStream stream)
        {
            var streamWriter = new StreamWriter(stream, Encoding.Default);

            // Render header
            streamWriter.Write("HTTP/{0} {1}\r\n", _version, _status);
            streamWriter.Write("Content-Type: {0}\r\n", _mimeType);
            streamWriter.Write("Content-Length: {0}\r\n", _content.Length);
            streamWriter.Write("\r\n");
            streamWriter.Flush();

            // Render content
            _content.Seek(0, SeekOrigin.Begin);
            _content.CopyTo(stream);
            stream.Flush();

            // Create new content
            _content = new MemoryStream();
            
        }

        
    }
}
